package com.tyros.common.kit.time;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author zhangshuaiyin
 * @date 2021-06-22 17:05
 */
public class DateKit {
    /**
     * Date -> LocalDate
     * Date -> Instant -> ZonedDateTime -> LocalDate/LocalDateTime
     *
     * @param date date
     * @return LocalDate/LocalDateTime
     */
    public static LocalDate toLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static String format(LocalDateTime date) {
        return format(date, null);
    }

    public static String format(LocalDateTime date, String pattern) {
        if (date == null) {
            return "";
        } else {
            if (StringUtils.isBlank(pattern)) {
                pattern = "yyyy-MM-dd HH:mm:ss";
            }
            return DateTimeFormatter.ofPattern(pattern).format(date);
        }
    }

    /**
     * LocalDateTime -> Date
     * LocalDate/LocalDateTime -> ZonedDateTime -> Instant -> Date
     *
     * @param localDate LocalDate/localDateTime
     * @return Date
     */
    public static Date toDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static Date toDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static String format(Date date) {
        return format(date, null);
    }

    public static String format(Date date, String pattern) {
        if (date == null) {
            return "";
        } else {
            if (StringUtils.isBlank(pattern)) {
                pattern = "yyyy-MM-dd HH:mm:ss";
            }
            return (new SimpleDateFormat(pattern)).format(date);
        }
    }
}
